﻿using System;
using System.ComponentModel;
using System.Diagnostics;

namespace NanoMvvm.ComponentModel
{
    internal class DynamicViewModelPropertyDescriptor<TWrapped> : WrapperPropertyDescriptorBase where TWrapped : class
    {
        private readonly WeakReference<IDynamicObject> ownerTarget;
 
        public DynamicViewModelPropertyDescriptor(IDynamicObject dynamicInstance, PropertyDescriptor baseDescriptor)
            : base(baseDescriptor)
        {
            if (dynamicInstance == null) throw new ArgumentNullException("dynamicInstance");

            ownerTarget = new WeakReference<IDynamicObject>(dynamicInstance);
        }

        public override void SetValue(object component, object value)
        {
            var obj = component as DynamicViewModel<TWrapped>;

            base.SetValue(obj.WrappedModel, value);

            if(ownerTarget.IsTargetAlive)
                ownerTarget.Target.RaisePropertyChanged(Name);
            else
                throw new InvalidOperationException("DynamicViewModel instance garbage collected.");
        }

        public override object GetValue(object component)
        {
            var obj = component as DynamicViewModel<TWrapped>;

            return base.GetValue(obj.WrappedModel);
        }
    }
}